package com.lzy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzy.common.QueryPageParam;
import com.lzy.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.lzy.dto.UserDto;
import com.lzy.entity.Result;
import com.lzy.service.IUserService;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-05-06
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(ClassController.class);

    @Autowired
    private IUserService userService;

   @PostMapping("/login")
   public Result login(@RequestBody UserDto userDto) {
        return userService.login(userDto);
   }

    @PostMapping("/register")
    public Result register(@RequestBody UserDto userDto) {
        return userService.register(userDto);
    }

    @DeleteMapping("/logout/{id}")
    public Result logout(@PathVariable("id") Integer id) {
        return userService.logout(id);
    }

    // 查询所有用户
    @GetMapping("/list")
    public Result list(){
         return Result.success(userService.list());
    }

    @GetMapping("/checkUserName")
    public Result checkUserName(@RequestParam String userName) {
        log.info("用户名唯一性校验：{}", userName);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, userName);
        User one = userService.getOne(queryWrapper);
        return one == null ? Result.success() : Result.success("该用户名已经存在,请更换用户名");
    }
    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query) {
        Page<User> page = new Page<>(query.getPageNum(), query.getPageSize());
        IPage<User> result = userService.getPage(page, query.getParam());
        return Result.success(result.getRecords(), result.getTotal());
    }

    @PostMapping("/create")
    public Result createUser(@RequestBody UserDto userDto) {
        return userService.createUser(userDto);
    }

    @PostMapping("/update")
    public Result updateUser(@RequestBody UserDto userDto) {
        return userService.updateUser(userDto);
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteUser(@PathVariable("id") Integer id) {
        return userService.deleteUser(id);
    }
}
